package com.example.administrator.szb.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.constraint.Guideline;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.example.administrator.szb.R;
import com.example.administrator.szb.bean.RzBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.ChangeStatuUtil;
import com.example.administrator.szb.util.DialogUtil;
import com.example.zhouwei.library.CustomPopWindow;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import dmax.dialog.SpotsDialog;

/**
 * Created by D N on 2017/9/13.
 * 顾问身份认证上传的图片的界面
 */

public class IdCardRzActivity extends TakePhotoActivity {
    TakePhoto take = getTakePhoto();
    String iconPath = "";//从相机或相册中获取的图片路径
    String icon_Path = "";//用户头像
    String image_z_Path = "";//身份证正面
    String image_f_Path = "";//身份证反面
    // public static final int TAKE_PHOTO = 1;//启动相机带的Ccde
    protected Uri imageUri;
    @Bind(R.id.imageView2)
    CircleImageView imageView2;
    @Bind(R.id.textView6)
    TextView textView6;
    @Bind(R.id.editText)
    EditText editText;
    @Bind(R.id.view)
    View view;
    @Bind(R.id.textView20)
    TextView textView20;
    @Bind(R.id.view2)
    View view2;
    @Bind(R.id.textView22)
    TextView textView22;
    @Bind(R.id.textView23)
    TextView textView23;
    @Bind(R.id.textView24)
    TextView textView24;
    @Bind(R.id.space14)
    View space14;
    @Bind(R.id.imageView7)
    ImageView imageView7;
    @Bind(R.id.space15)
    View space15;
    @Bind(R.id.imageView15)
    ImageView imageView15;
    @Bind(R.id.button)
    Button button;

    private static int type = 0;//用于确定那个imageview 被点击，进而确定glide.into(imageview);
    ArrayList<String> id_card_info_rz = new ArrayList<>();

    AlertDialog dialog;//进度条
    InputMethodManager imm;//软键盘
    @Bind(R.id.id_card_fh)
    ImageView idCardFh;
    @Bind(R.id.guideline)
    Guideline guideline;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rz_activity_choose_image);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ButterKnife.bind(this);

        SampleApplicationLike.getActivitiesInstance().add(this);
        imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);//软键盘实例
    }


    /**
     * 文件路径转成bitmap,图片选择器中使用
     *
     * @param path
     * @return
     */
    public Bitmap getBitmapFromPath(String path) {

        if (!new File(path).exists()) {
            System.err.println("getBitmapFromPath: file not exists");
            return null;
        }
        // Bitmap bitmap = Bitmap.createBitmap(1366, 768, Config.ARGB_8888);
        // Canvas canvas = new Canvas(bitmap);
        // Movie movie = Movie.decodeFile(path);
        // movie.draw(canvas, 0, 0);
        //
        // return bitmap;

        byte[] buf = new byte[1024 * 1024];// 1M
        Bitmap bitmap = null;

        try {

            FileInputStream fis = new FileInputStream(path);
            int len = fis.read(buf, 0, buf.length);
            bitmap = BitmapFactory.decodeByteArray(buf, 0, len);
            if (bitmap == null) {
                System.out.println("len= " + len);
                System.err.println("path: " + path + "  could not be decode!!!");
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return bitmap;
    }

    /**
     * 将bitmap转成字符数组
     *
     * @param bmp
     * @return
     */
    public byte[] getImageBytes(Bitmap bmp) {

        if (bmp == null) return null;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);

        byte[] imageBytes = baos.toByteArray();


        return Base64.encode(imageBytes, Base64.DEFAULT);

    }


    /**
     * 拍照或者从相册中获取图片后的回调方法
     *
     * @param result
     */
    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        iconPath = result.getImage().getOriginalPath();
        // Toasts.show(this, "imagePath:" +  getBitmapFromPath(iconPath).getByteCount(), Toast.LENGTH_LONG ).show();
        switch (type) {
            case 0:
                icon_Path = iconPath;//将获取到的路径赋值给头像
                Glide.with(this).load(new File(iconPath)).into(imageView2);
                break;
            case 1:
                image_z_Path = iconPath;
                Glide.with(this).load(new File(iconPath)).into(imageView7);
                break;
            case 2:
                image_f_Path = iconPath;
                Glide.with(this).load(new File(iconPath)).into(imageView15);
                break;
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }


    /**
     * 图片点击
     *
     * @param view
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @OnClick({R.id.imageView2, R.id.imageView7, R.id.imageView15, R.id.button, R.id.textView24,R.id.id_card_fh})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.imageView2:
                type = 0;
                if (imm.isActive() && getCurrentFocus() != null) {
                    if (getCurrentFocus().getWindowToken() != null) {
                        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
                showPopupwindow();
                break;
            case R.id.imageView7:
                type = 1;
                if (imm.isActive() && getCurrentFocus() != null) {
                    if (getCurrentFocus().getWindowToken() != null) {
                        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
                showPopupwindow();
                break;
            case R.id.imageView15:
                type = 2;
                if (imm.isActive() && getCurrentFocus() != null) {
                    if (getCurrentFocus().getWindowToken() != null) {
                        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                }
                showPopupwindow();
                break;
            case R.id.button:
                tjzl();//执行提交资料
                //startActivity(new Intent(this,IdCardRzSuccessActivity.class));
                break;
            case R.id.textView24:
                startActivity(new Intent(IdCardRzActivity.this, PZYQActivity.class));
                break;
            case R.id.id_card_fh:
                finish();
                break;
        }
    }

    private void tjzl() {
        boolean flag = checkInfo();
        if (flag) {
            requestTjzl();
        }
    }

    /**
     * 执行请求
     */
    private void requestTjzl() {
        showProgressbar();
        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        //map.put("id",51+"");//测试用的用户id
        map.put("id", SampleApplicationLike.getUserloginInstance().getId() + "");
        map.put("id_number", "622723199409272214");
        map.put("name", id_card_info_rz.get(1));
        String icon_Path_image = ChangeStatuUtil.bitmapToString(icon_Path);
        map.put("zhenshi_img", icon_Path_image);
        String image_z_Path_img = ChangeStatuUtil.bitmapToString(image_z_Path);
        map.put("identity_z", image_z_Path_img);
        String image_f_Path_img = ChangeStatuUtil.bitmapToString(image_f_Path);
        map.put("identity_f", image_f_Path_img);
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, RzBean.class, URLAddress.URLBASE + URLAddress.URL_GJ_RZ, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                RzBean rzBean = (RzBean) response;
                if (rzBean.getResult() == 1) {
                    dialog.dismiss();
                    startActivity(new Intent(IdCardRzActivity.this, IdCardRzSuccessActivity.class));
                } else {
                    dialog.dismiss();
                    DialogUtil.showSimpleDialog(IdCardRzActivity.this, rzBean.getErr_msg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dialog.dismiss();
                DialogUtil.showToast(IdCardRzActivity.this,error.toString());
                Log.e("提交认证错误", error.toString());
            }
        });
    }


    /**
     * 显示进度条
     */
    private void showProgressbar() {
        dialog = new SpotsDialog(this, R.style.Custom);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        // WindowManager m = getWindowManager();
//        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
//        android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
//        p.height = 300;   //高度设置为屏幕的0.3
//        p.width = 500;    //宽度设置为屏幕的0.5
//        dialog.getWindow().setAttributes(p);
    }

    /**
     * 检查信息
     *
     * @return
     */
    private boolean checkInfo() {
        getInfo();
        if (TextUtils.isEmpty(id_card_info_rz.get(0))) {
            DialogUtil.showSimpleDialog(this, "请上传头像");
        } else if (TextUtils.isEmpty(id_card_info_rz.get(1))) {
            DialogUtil.showSimpleDialog(this, "请输入真实姓名");
        } else if (TextUtils.isEmpty(id_card_info_rz.get(2))) {
            DialogUtil.showSimpleDialog(this, "请上传身份证正面");
        } else if (TextUtils.isEmpty(id_card_info_rz.get(3))) {
            DialogUtil.showSimpleDialog(this, "请上传身份证背面");
        } else {
            return true;
        }
        return false;
    }

    /**
     * 获取填入的信息
     */
    private void getInfo() {
        id_card_info_rz.clear();
        //加头像
        if (imageView2.getDrawable().getCurrent().getConstantState() == getResources().getDrawable(R.drawable.mrtx).getConstantState()) {
            id_card_info_rz.add(null);
        } else {
            // String image_buff = new String(getImageBytes(getBitmapFromPath(iconPath)));
            id_card_info_rz.add("has data");
        }
        id_card_info_rz.add(editText.getText().toString().trim());
        if (imageView7.getDrawable().getCurrent().getConstantState() == getResources().getDrawable(R.drawable.sfz_zm).getConstantState()) {
            id_card_info_rz.add(null);
        } else {
            // String image_buff = new String(getImageBytes(getBitmapFromPath(iconPath)));
            id_card_info_rz.add("has data");
        }
        if (imageView15.getDrawable().getCurrent().getConstantState() == getResources().getDrawable(R.drawable.sfz_fm).getConstantState()) {
            id_card_info_rz.add(null);
        } else {
            // String image_buff = new String(getImageBytes(getBitmapFromPath(iconPath)));
            id_card_info_rz.add("has data");
        }
    }

    /**
     * 初始化popupwindow弹出框
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void showPopupwindow() {
        View popwindow_view = LayoutInflater.from(this).inflate(R.layout.view_popupwindow_picture_choose, null);
        View rootview = LayoutInflater.from(this).inflate(R.layout.rz_activity_choose_image, null);

        CustomPopWindow popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(popwindow_view)//显示的布局，还可以通过设置一个View
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) //设置显示的大小，不设置就默认包裹内容
                .setFocusable(true)//是否获取焦点，默认为ture
                .setOutsideTouchable(true)//是否PopupWindow 以外触摸dissmiss
                .create()//创建PopupWindow
                .showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        //显示PopupWindow

        handleLogic(popwindow_view, popWindow);

    }

    /**
     * 处理弹出显示内容、点击事件等逻辑
     *
     * @param contentView
     */
    private void handleLogic(View contentView, final CustomPopWindow mCustomPopWindow) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCustomPopWindow != null) {
                    mCustomPopWindow.dissmiss();
                }
                String showContent = "";
                switch (v.getId()) {
                    case R.id.textView26:
                        takePhoto();
                        break;
                    case R.id.textView27:
                        // showContent = "点击 Item菜单2";
                        chooseImage();
                        break;
                    case R.id.textView28:
                        mCustomPopWindow.dissmiss();
                        break;
                }
                //Toasts.show(MingPianActivity.this, showContent, Toast.LENGTH_SHORT);
            }
        };
        contentView.findViewById(R.id.textView26).setOnClickListener(listener);
        contentView.findViewById(R.id.textView27).setOnClickListener(listener);
        contentView.findViewById(R.id.textView28).setOnClickListener(listener);

    }

    /**
     * 开启图片选择
     */
    private void chooseImage() {
        //take.onPickFromGallery();
        CropOptions cropOptions=new CropOptions.Builder().setAspectX(9999).setAspectY(9998).setWithOwnCrop(false).create();
        take.onPickFromGalleryWithCrop(getImageUri(),cropOptions);
    }


    /**
     * 开启相机拍照
     */
    public void takePhoto() {
        //take.onPickFromCapture(getImageUri());//执行拍照
        CropOptions cropOptions=new CropOptions.Builder().setAspectX(9999).setAspectY(9998).setWithOwnCrop(false).create();
        take.onPickFromCaptureWithCrop(getImageUri(),cropOptions);
    }

    /**
     * 返回一个Uri给take调用
     */
    public Uri getImageUri() {
        File file = getImgFile();
        imageUri = Uri.fromFile(file);
        return imageUri;

    }

    /**
     * 设置文件存储路径，返回一个file
     *
     * @return
     */
    private File getImgFile() {
        File file = new File(Environment.getExternalStorageDirectory() + "/szb/image");
        if (!file.exists()) {
            //要点！
            file.mkdirs();
        }
        File imgFile = new File(file, "image" + System.currentTimeMillis() + ".jpg");
        return imgFile;

    }
}
